import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:my_blog_flutter/app/modules/home/models/home_entity.dart';

import '../../../net/api_service.dart';
import '../../../net/httpsClient.dart';
import '../../../services/user_utils.dart';
import '../../../services/utils.dart';

class HomeController extends GetxController {
  // 响应式数据
  final homeList = <HomeDataList>[].obs;
  final isLoading = false.obs;
  final totalCount = 0.obs;

  // 搜索相关
  final searchController = TextEditingController();
  final isSearching = false.obs;
  final searchKeyword = ''.obs;
  final searchText = ''.obs;

  @override
  void onInit() {
    super.onInit();
    // 检查登录状态
    _checkLoginStatus();
    // 页面初始化时获取数据
    getHomeList();
  }

  @override
  void onClose() {
    searchController.dispose();
    super.onClose();
  }

  // 检查登录状态
  Future<void> _checkLoginStatus() async {
    final token = await UserUtils.getToken();
    final loginInfo = await UserUtils.getLoginInfo();

    myLog('=== 登录状态检查 ===');
    myLog('Token: ${token ?? "无token"}');
    myLog('登录信息: ${loginInfo?.toString() ?? "无登录信息"}');
    myLog('Token长度: ${token?.length ?? 0}');
    myLog('==================');
  }

  Future<void> getHomeList({
    String title = "",
    int pageIndex = 1,
    int pageSize = 10,
    int state = -1,
    bool isRefresh = false,
  }) async {
    if (!isRefresh) {
      isLoading.value = true;
    }

    try {
      final homeData = {
        "title": title,
        "pageIndex": pageIndex,
        "pageSize": pageSize,
        "state": state,
      };

      myLog('请求首页数据: $homeData');

      final response =
          await HttpsClient().post(ApiService.post, data: homeData);

      // 检查响应是否为空
      if (response == null || response.data == null) {
        myLog('服务器响应为空');
        SmartDialog.showToast(
          '服务器连接失败，请检查网络或服务器状态',
          alignment: Alignment.center,
        );
        return;
      }

      myLog('服务器响应: ${response.data}');

      final entity = HomeEntity.fromJson(response.data);
      myLog('解析后的响应码: ${entity.code}, 消息: ${entity.message}');

      if (entity.code == 100 && entity.data != null) {
        if (isRefresh || pageIndex == 1) {
          // 刷新或第一页，替换数据
          homeList.value = entity.data!.list ?? [];
        } else {
          // 加载更多，追加数据
          homeList.addAll(entity.data!.list ?? []);
        }
        totalCount.value = entity.data!.totalCount ?? 0;

        myLog('获取首页数据成功，共 ${homeList.length} 条');
      } else {
        // 处理各种错误情况
        String errorMsg = entity.message ?? '获取首页数据失败';

        if (entity.code == 99) {
          errorMsg = '授权失败，请重新登录';
          myLog('授权失败，可能需要重新登录');
        } else if (entity.code == 101) {
          errorMsg = '请先登录';
          myLog('用户未登录');
        }

        SmartDialog.showToast(
          errorMsg,
          alignment: Alignment.center,
        );
        myLog('获取首页数据失败，错误码: ${entity.code}, 错误信息: ${entity.message}');
      }
    } catch (e, stackTrace) {
      myLog('获取首页数据失败: $e');
      myLog('堆栈跟踪: $stackTrace');
      SmartDialog.showToast(
        '获取数据失败: $e',
        alignment: Alignment.center,
      );
    } finally {
      isLoading.value = false;
    }
  }

  // 刷新数据
  Future<void> refreshData() async {
    await getHomeList(isRefresh: true);
  }

  // 搜索文章
  void searchArticles() {
    final keyword = searchController.text.trim();
    if (keyword.isEmpty) {
      // 如果搜索词为空，显示所有文章
      searchKeyword.value = '';
      getHomeList(title: '', isRefresh: true);
    } else {
      // 执行搜索
      searchKeyword.value = keyword;
      getHomeList(title: keyword, isRefresh: true);
    }
  }

  // 清空搜索
  void clearSearch() {
    searchController.clear();
    searchKeyword.value = '';
    searchText.value = '';
    getHomeList(title: '', isRefresh: true);
  }

  // 实时搜索（可选，用于输入时实时搜索）
  void onSearchChanged(String value) {
    searchText.value = value; // 更新搜索文本状态，用于UI响应

    // 防抖处理，避免频繁请求
    if (value.trim() != searchKeyword.value) {
      searchKeyword.value = value.trim();
      // 延迟500毫秒后执行搜索
      Future.delayed(const Duration(milliseconds: 500), () {
        if (searchKeyword.value == value.trim()) {
          getHomeList(title: searchKeyword.value, isRefresh: true);
        }
      });
    }
  }
}
